﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.ComponentModel.Composition;
using DSCop.Core;

namespace DSCop.CoreRules
{
    [Export(typeof(IDSRule))]
    [ExportMetadata("RuleName", "TeradataConnectorParametersRule")]
    public class TeradataConnectorParametersRule : IDSRule
    {
        #region IDSRule Members

        public IList<RuleViolation> ValidateJob(XElement job)
        {
            IList<XElement> tdConnectorStages = DSCopUtil.GetStagesByType(job, "TeradataConnectorPX");

            IList<RuleViolation> violations = new List<RuleViolation>();
            foreach (XElement stage in tdConnectorStages)
            {
                var stageProperties = stage
                    .Descendants("Collection")
                    .Descendants("SubRecord");

                string propertyValue = DSCopUtil.GetStagePropertyValue(stage, "XMLProperties");
                XDocument dynamicProperties = XDocument.Parse(propertyValue);

                bool IsServerHardcoded = dynamicProperties
                    .Descendants("Connection")
                    .Single()
                    .Element("Server").Value.StartsWith("#") == false;
                if (IsServerHardcoded)
                {
                    violations.Add(new RuleViolation
                    {
                        JobName = DSCopUtil.GetJobName(job),
                        Message = "Stage \"" + DSCopUtil.GetStageName(stage) + "\" uses hardcoded server name."
                    });
                }

                bool IsUsernameHardcoded = dynamicProperties
                    .Descendants("Connection")
                    .Single()
                    .Element("Username").Value.StartsWith("#") == false;
                if (IsUsernameHardcoded)
                {
                    violations.Add(new RuleViolation
                    {
                        JobName = DSCopUtil.GetJobName(job),
                        Message = "Stage \"" + DSCopUtil.GetStageName(stage) + "\" uses hardcoded username."
                    });
                }


                bool IsPasswordHardcoded = dynamicProperties
                    .Descendants("Connection")
                    .Single()
                    .Element("Password").Value.StartsWith("#") == false;
                if (IsPasswordHardcoded)
                {
                    violations.Add(new RuleViolation
                    {
                        JobName = DSCopUtil.GetJobName(job),
                        Message = "Stage \"" + DSCopUtil.GetStageName(stage) + "\" uses hardcoded password."
                    });
                }

            }

            return violations;
        }

        #endregion
    }
}
